<template>
  <div
    id="response_by_dims_chart"
    class="echarts"
  ></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, watch } from 'vue'

interface Props {
  metricsData: {
    vea_response_total_by_dims: Array<{
      labels: {
        code: string
        method: string
        path: string
      }
      value: number
    }>
  } | null
}

const props = defineProps<Props>()

const chartDom = ref<HTMLElement | null>(null)
const myChart = ref<echarts.ECharts | null>(null)

interface ResponseData {
  code: string
  method: string
  path: string
  value: number
}

// 图表配置
const getChartOption = (data: ResponseData[]) => {
  // 按状态码分组统计
  const codeGroups = data.reduce((acc: { [key: string]: number }, curr) => {
    acc[curr.code] = (acc[curr.code] || 0) + curr.value
    return acc
  }, {})

  return {
    title: {
      text: '响应状态码',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: Object.keys(codeGroups),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '响应数'
    },
    series: [
      {
        name: '响应数',
        type: 'bar',
        data: Object.values(codeGroups),
        itemStyle: {
          color: function (params: { dataIndex: number }) {
            const code = Object.keys(codeGroups)[params.dataIndex]
            // 根据状态码设置不同颜色
            if (code.startsWith('2')) return '#91cc75' // 2xx 绿色
            if (code.startsWith('3')) return '#5470c6' // 3xx 蓝色
            if (code.startsWith('4')) return '#fac858' // 4xx 黄色
            if (code.startsWith('5')) return '#ee6666' // 5xx 红色
            return '#73c0de' // 其他 浅蓝色
          }
        }
      }
    ]
  }
}

// 更新数据
const updateData = () => {
  if (!props.metricsData) return

  const responseData: ResponseData[] = props.metricsData.vea_response_total_by_dims.map(item => ({
    code: item.labels.code,
    method: item.labels.method,
    path: item.labels.path,
    value: item.value
  }))
  myChart.value?.setOption(getChartOption(responseData))
}

// 监听数据变化
watch(() => props.metricsData, () => {
  updateData()
}, { deep: true })

// 初始化图表
const initChart = () => {
  if (!chartDom.value) return

  myChart.value = echarts.init(chartDom.value)
  myChart.value.setOption(getChartOption([]))

  // 添加窗口大小变化的监听
  window.addEventListener('resize', () => {
    myChart.value?.resize()
  })
}

onMounted(() => {
  chartDom.value = document.getElementById('response_by_dims_chart')
  initChart()
  if (props.metricsData) {
    updateData()
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    myChart.value?.resize()
  })
  myChart.value?.dispose()
})
</script>

<style scoped>
.echarts {
  width: 100%;
  height: 320px;
}
</style>